import { useParams, useNavigate, useLocation } from "react-router-dom";
import {
  Typography,
  Tag,
  Space,
  Divider,
  Spin,
  Button,
  message,
  Card,
  List,
  Form,
  Input,
  InputNumber,
  Rate,
  Avatar,
  Pagination,
  Empty,
  Select,
  Row,
  Col,
} from "antd";
import { useEffect, useState } from "react";
import {
  fetchArticleById,
  downloadArticleWordById,
  downloadArticleMarkdownById,
  downloadArticlePdfById,
} from "../api/articles";
import {
  getCommentsByArticleId,
  createComment,
  getAiCommentsByArticleId,
  generateAiComments,
} from "../api/comments";
import dayjs from "dayjs";
import ReactMarkdown from "react-markdown";
import {
  ArrowLeftOutlined,
  StarOutlined,
  UserOutlined,
  MessageOutlined,
  SortAscendingOutlined,
  RobotOutlined,
  GoogleOutlined,
  AppleOutlined,
  AndroidOutlined,
  BgColorsOutlined,
} from "@ant-design/icons";
import { useTheme } from "../contexts/ThemeContext";
import { isAdmin, getCurrentUsername } from "../utils/auth";

const { TextArea } = Input;

export default function ArticleDetail() {
  const { isDarkMode } = useTheme();
  const { id } = useParams();
  const navigate = useNavigate();
  const location = useLocation();
  const [article, setArticle] = useState(null);
  const [loading, setLoading] = useState(true);
  const [downloading, setDownloading] = useState(false);

  // Word 下载 loading
  const [wordDownloading, setWordDownloading] = useState(false);

  // markdown 下载 loading
  const [mdDownloading, setMdDownloading] = useState(false);

  // PDF 下载 loading
  const [pdfDownloading, setPdfDownloading] = useState(false);

  // 评论相关状态
  const [comments, setComments] = useState([]);
  const [commentsLoading, setCommentsLoading] = useState(false);
  const [commentSubmitting, setCommentSubmitting] = useState(false);
  const [commentParams, setCommentParams] = useState({
    page: 1,
    size: 5,
    sortWay: "create_time", // 新增排序方式
  });
  const [commentsTotal, setCommentsTotal] = useState(0);

  // AI 评论相关状态
  const [aiComments, setAiComments] = useState([]);
  const [aiCommentsLoading, setAiCommentsLoading] = useState(false);
  const [generatingAiComments, setGeneratingAiComments] = useState(false);

  // 表单引用
  const [commentForm] = Form.useForm();

  // 获取文章评论
  const fetchComments = async (params = commentParams) => {
    setCommentsLoading(true);
    try {
      const response = await getCommentsByArticleId(id, params);
      const commentsList = response.data.list || [];
      console.log("📝 获取到的评论列表:", commentsList);

      // 打印第一条评论的完整结构
      if (commentsList.length > 0) {
        console.log(
          "🔍 第一条评论的完整数据结构:",
          JSON.stringify(commentsList[0], null, 2)
        );
        console.log("📋 评论对象的所有键:", Object.keys(commentsList[0]));
      }

      setComments(commentsList);
      setCommentsTotal(response.data.total || 0);
    } catch (error) {
      console.error("获取评论失败:", error);
      message.error(error.message || "获取评论失败");
    } finally {
      setCommentsLoading(false);
    }
  };

  // 获取AI评论
  const fetchAiComments = async () => {
    setAiCommentsLoading(true);
    try {
      const response = await getAiCommentsByArticleId(id);
      const aiCommentsList = response.data || [];
      console.log("🤖 获取到的AI评论列表:", aiCommentsList);
      setAiComments(aiCommentsList);
    } catch (error) {
      console.error("获取AI评论失败:", error);
      // 静默处理错误，如果没有AI评论就显示空
      setAiComments([]);
    } finally {
      setAiCommentsLoading(false);
    }
  };

  // 生成AI评论
  const handleGenerateAiComments = async () => {
    setGeneratingAiComments(true);
    try {
      await generateAiComments(id);
      message.success("AI评论生成成功,正在获取评论内容...");
      // 等待1秒后再重新获取AI评论,给后端处理时间
      await new Promise((resolve) => setTimeout(resolve, 1000)); // 等待1秒
      await fetchAiComments();
      message.success("AI评论已加载完成");
    } catch (error) {
      console.error("生成AI评论失败:", error);
      message.error(error.message || "生成AI评论失败");
    } finally {
      setGeneratingAiComments(false);
    }
  };

  // 检查是否可以生成AI评论（管理员或文章作者）
  const canGenerateAiComments = () => {
    if (isAdmin()) {
      return true;
    }
    const currentUsername = getCurrentUsername();
    return currentUsername && article && article.username === currentUsername;
  };

  // 获取AI图标和颜色
  const getAiIconAndColor = (aiType) => {
    const iconMap = {
      Coze: { icon: <GoogleOutlined />, color: "#4285F4", bgColor: "#E8F0FE" },
      Gemini: {
        icon: <AndroidOutlined />,
        color: "#EA4335",
        bgColor: "#FCE8E6",
      },
      Tongyi: { icon: <AppleOutlined />, color: "#FF6B35", bgColor: "#FFE8E0" },
      default: {
        icon: <RobotOutlined />,
        color: "#722ED1",
        bgColor: "#F9F0FF",
      },
    };
    return iconMap[aiType] || iconMap.default;
  };

  // 提交评论
  const handleCommentSubmit = async (values) => {
    // 检查登录状态
    const userId = localStorage.getItem("userId");
    const username = localStorage.getItem("username");

    if (!userId || !username) {
      message.error("请先登录");
      return;
    }

    setCommentSubmitting(true);
    try {
      await createComment({
        content: values.content,
        star: values.star,
        articleTitle: article.title,
        username: username,
      });

      message.success("评论发布成功");
      commentForm.resetFields();
      // 重新获取评论列表
      setCommentParams({ ...commentParams, page: 1 });
      await fetchComments({ ...commentParams, page: 1 });
    } catch (error) {
      console.error("发布评论失败:", error);
      message.error(error.message || "发布评论失败");
    } finally {
      setCommentSubmitting(false);
    }
  };

  // 评论分页变化
  const handleCommentPageChange = (page, pageSize) => {
    const newParams = { ...commentParams, page, size: pageSize };
    setCommentParams(newParams);
    fetchComments(newParams);
  };

  // 评论排序变化
  const handleSortChange = (sortWay) => {
    const newParams = { ...commentParams, sortWay, page: 1 }; // 切换排序时重置到第一页
    setCommentParams(newParams);
    fetchComments(newParams);
  };

  // 获取来源页面信息
  // 下载文章Word
  const handleDownloadWord = async () => {
    setWordDownloading(true);
    try {
      const url = await downloadArticleWordById(id);
      if (url) {
        // 创建a标签下载
        const link = document.createElement("a");
        link.href = url;
        link.download = `article-${id}.docx`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        message.success("Word 下载已开始");
      } else {
        message.error("未获取到Word下载链接");
      }
    } catch (e) {
      message.error(e.message || "Word 下载失败");
    } finally {
      setWordDownloading(false);
    }
  };

  // 下载 Markdown 文件
  const handleDownloadMarkdown = async () => {
    setMdDownloading(true);
    try {
      const url = await downloadArticleMarkdownById(id);
      if (url) {
        const link = document.createElement("a");
        link.href = url;
        link.download = `article-${id}.md`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        message.success("Markdown 下载已开始");
      } else {
        message.error("未获取到Markdown下载链接");
      }
    } catch (e) {
      message.error(e.message || "Markdown 下载失败");
    } finally {
      setMdDownloading(false);
    }
  };

  // 下载 PDF 文件
  const handleDownloadPdf = async () => {
    setPdfDownloading(true);
    try {
      const url = await downloadArticlePdfById(id);
      if (url) {
        const link = document.createElement("a");
        link.href = url;
        link.download = `article-${id}.pdf`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        message.success("PDF 下载已开始");
      } else {
        message.error("未获取到PDF下载链接");
      }
    } catch (e) {
      message.error(e.message || "PDF 下载失败");
    } finally {
      setPdfDownloading(false);
    }
  };
  const searchParams = new URLSearchParams(location.search);
  const fromPage = searchParams.get("from");

  useEffect(() => {
    setLoading(true);
    fetchArticleById(id)
      .then((data) => {
        setArticle(data);
        // 获取文章后，加载评论和AI评论
        fetchComments();
        fetchAiComments();
      })
      .finally(() => setLoading(false));
  }, [id]);

  if (loading) return <Spin style={{ marginTop: 100 }} />;
  if (!article) return <div>未找到文章</div>;

  // 智能返回功能
  const handleGoBack = () => {
    if (fromPage === "profile") {
      navigate("/profile");
    } else {
      navigate("/articles");
    }
  };

  // 动态返回按钮文本
  const getBackButtonText = () => {
    if (fromPage === "profile") {
      return "返回个人中心";
    }
    return "返回文章列表";
  };

  return (
    <div
      style={{
        width: "100%",
        background: isDarkMode ? "#1f1f1f" : "#fff",
        borderRadius: 12,
        boxShadow: isDarkMode
          ? "0 2px 12px rgba(0,0,0,0.3)"
          : "0 2px 12px #eee",
        borderColor: isDarkMode ? "#434343" : "#d9d9d9",
        padding: 40,
        boxSizing: "border-box",
        minHeight: 500,
        transition: "all 0.3s ease",
      }}>
      {/* 返回按钮 */}
      {/* 返回和下载按钮 */}
      <div style={{ marginBottom: 24, display: "flex", gap: 16 }}>
        <Button
          type="default"
          icon={<ArrowLeftOutlined />}
          onClick={handleGoBack}
          size="large">
          {getBackButtonText()}
        </Button>
        <Button
          type="primary"
          loading={wordDownloading}
          onClick={handleDownloadWord}
          style={{
            marginLeft: 8,
            backgroundColor: "#1890ff",
            borderColor: "#1890ff",
          }}>
          下载Word
        </Button>
        <Button
          type="primary"
          loading={mdDownloading}
          onClick={handleDownloadMarkdown}
          style={{
            marginLeft: 8,
            backgroundColor: "#52c41a",
            borderColor: "#52c41a",
          }}>
          下载Markdown
        </Button>
        <Button
          type="primary"
          loading={pdfDownloading}
          onClick={handleDownloadPdf}
          style={{
            marginLeft: 8,
            backgroundColor: "#fa541c",
            borderColor: "#fa541c",
          }}>
          下载PDF
        </Button>
      </div>

      <Row gutter={[32, 32]}>
        <Col xs={24} lg={16}>
          <Typography.Title level={2} style={{ marginBottom: 8 }}>
            {article.title}
          </Typography.Title>
          <Space size="large" style={{ marginBottom: 8 }}>
            <Typography.Text type="secondary">
              作者：{article.username}
            </Typography.Text>
            <Typography.Text type="secondary">
              状态：{article.status}
            </Typography.Text>
            <Typography.Text type="secondary">
              浏览量：{article.views}
            </Typography.Text>
          </Space>
          <div style={{ margin: "8px 0" }}>
            {article.tags.map((tag) => (
              <Tag color="blue" key={tag}>
                {tag}
              </Tag>
            ))}
          </div>
          <Divider />
          <div style={{ fontSize: 16, lineHeight: 2 }}>
            <ReactMarkdown>{article.content}</ReactMarkdown>
          </div>
          <Divider />
          <Typography.Text type="secondary" style={{ fontSize: 12 }}>
            创建时间：
            {article.createAt || article.create_at
              ? dayjs(article.createAt || article.create_at).format(
                  "YYYY-MM-DD HH:mm:ss"
                )
              : "-"}
            　最后更新：
            {article.updateAt || article.update_at
              ? dayjs(article.updateAt || article.update_at).format(
                  "YYYY-MM-DD HH:mm:ss"
                )
              : "-"}
          </Typography.Text>
        </Col>

        {/* AI 评论侧边栏 */}
        <Col xs={24} lg={8}>
          <Card
            title={
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <RobotOutlined />
                <span>AI 评论</span>
              </div>
            }
            style={{
              backgroundColor: isDarkMode ? "#262626" : "#fafafa",
              border: isDarkMode ? "1px solid #434343" : "1px solid #f0f0f0",
              position: "sticky",
              top: 20,
            }}>
            <Spin
              spinning={aiCommentsLoading || generatingAiComments}
              tip={
                generatingAiComments ? "AI正在生成评论,请稍候..." : "加载中..."
              }>
              {aiComments.length > 0 ? (
                <>
                  <div
                    style={{
                      display: "flex",
                      justifyContent: "flex-end",
                      marginBottom: 12,
                    }}>
                    <Button
                      type="primary"
                      size="small"
                      icon={<RobotOutlined />}
                      onClick={handleGenerateAiComments}
                      loading={generatingAiComments}
                      disabled={generatingAiComments}
                      style={{
                        backgroundColor: "#722ED1",
                        borderColor: "#722ED1",
                      }}>
                      重新生成
                    </Button>
                  </div>
                  <div
                    style={{
                      maxHeight: "calc(100vh - 200px)",
                      overflowY: "auto",
                    }}>
                    {aiComments.map((aiComment, index) => {
                      const { icon, color, bgColor } = getAiIconAndColor(
                        aiComment.aiType
                      );
                      return (
                        <div
                          key={index}
                          style={{
                            marginBottom: 16,
                            paddingBottom: 16,
                            borderBottom: isDarkMode
                              ? "1px solid #434343"
                              : "1px solid #f0f0f0",
                          }}>
                          <div
                            style={{
                              display: "flex",
                              alignItems: "center",
                              marginBottom: 8,
                              gap: 8,
                            }}>
                            {aiComment.pic ? (
                              <Avatar
                                src={aiComment.pic}
                                style={{
                                  backgroundColor: bgColor,
                                }}
                              />
                            ) : (
                              <Avatar
                                style={{
                                  backgroundColor: bgColor,
                                  color: color,
                                  fontSize: 16,
                                }}
                                icon={icon}
                              />
                            )}
                            <Typography.Text
                              strong
                              style={{
                                color: isDarkMode ? "#fff" : "#000",
                                fontSize: 14,
                              }}>
                              {aiComment.aiType}
                            </Typography.Text>
                          </div>
                          <div
                            style={{
                              display: "flex",
                              alignItems: "center",
                              gap: 6,
                              marginBottom: 8,
                            }}>
                            <Rate
                              disabled
                              value={aiComment.star / 2}
                              allowHalf
                              style={{ fontSize: 12 }}
                            />
                            <Typography.Text
                              type="secondary"
                              style={{ fontSize: 11 }}>
                              {typeof aiComment.star === "number"
                                ? aiComment.star.toFixed(1)
                                : aiComment.star}
                              分
                            </Typography.Text>
                          </div>
                          <Typography.Paragraph
                            style={{
                              lineHeight: 1.5,
                              color: isDarkMode ? "#aaa" : "#666",
                              marginBottom: 0,
                              fontSize: 12,
                              textAlign: "justify",
                            }}>
                            {aiComment.content}
                          </Typography.Paragraph>
                        </div>
                      );
                    })}
                  </div>
                </>
              ) : (
                <div style={{ textAlign: "center", padding: "20px 0" }}>
                  <Empty
                    description="暂无AI评论"
                    style={{ marginBottom: 16 }}
                  />
                  {canGenerateAiComments() && (
                    <Button
                      type="primary"
                      icon={<RobotOutlined />}
                      onClick={handleGenerateAiComments}
                      loading={generatingAiComments}
                      disabled={generatingAiComments}>
                      生成AI评论
                    </Button>
                  )}
                </div>
              )}
            </Spin>
          </Card>
        </Col>
      </Row>

      {/* 用户评论区域 */}
      <div style={{ marginTop: 40 }}>
        <Typography.Title level={3} style={{ marginBottom: 20 }}>
          <MessageOutlined style={{ marginRight: 8 }} />
          评论 ({commentsTotal})
        </Typography.Title>

        {/* 发表评论 */}
        <Card
          title="发表评论"
          style={{
            marginBottom: 20,
            backgroundColor: isDarkMode ? "#262626" : "#fafafa",
            border: isDarkMode ? "1px solid #434343" : "1px solid #f0f0f0",
          }}>
          <Form
            form={commentForm}
            onFinish={handleCommentSubmit}
            layout="vertical"
            initialValues={{ star: 5 }}>
            <Form.Item
              name="content"
              label="评论内容"
              rules={[
                { required: true, message: "请输入评论内容" },
                { max: 1000, message: "评论内容不能超过1000个字符" },
              ]}>
              <TextArea
                placeholder="请输入您的评论..."
                rows={4}
                showCount
                maxLength={1000}
              />
            </Form.Item>

            <Form.Item
              name="star"
              label="评分"
              rules={[{ required: true, message: "请选择评分" }]}>
              <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                <Rate
                  allowHalf
                  count={5}
                  onChange={(value) =>
                    commentForm.setFieldValue("star", value * 2)
                  }
                />
                <InputNumber
                  min={0}
                  max={10}
                  step={0.1}
                  precision={1}
                  placeholder="0-10"
                  style={{ width: 80 }}
                  onChange={(value) => commentForm.setFieldValue("star", value)}
                />
                <span style={{ color: isDarkMode ? "#888" : "#666" }}>
                  (0-10分)
                </span>
              </div>
            </Form.Item>

            <Form.Item style={{ marginBottom: 0 }}>
              <Button
                type="primary"
                htmlType="submit"
                loading={commentSubmitting}
                size="large">
                发布评论
              </Button>
            </Form.Item>
          </Form>
        </Card>

        {/* 评论列表 */}
        <Card
          title={
            <Row justify="space-between" align="middle">
              <Col>
                <span>全部评论 ({commentsTotal})</span>
              </Col>
              <Col>
                <Space>
                  <SortAscendingOutlined />
                  <span
                    style={{
                      fontSize: 14,
                      color: isDarkMode ? "#888" : "#666",
                    }}>
                    排序：
                  </span>
                  <Space size={0}>
                    <Button
                      type={
                        commentParams.sortWay === "create_time"
                          ? "primary"
                          : "default"
                      }
                      size="small"
                      onClick={() => handleSortChange("create_time")}
                      style={{
                        borderRadius: "4px 0 0 4px",
                        borderRight: "none",
                      }}>
                      时间
                    </Button>
                    <Button
                      type={
                        commentParams.sortWay === "star" ? "primary" : "default"
                      }
                      size="small"
                      onClick={() => handleSortChange("star")}
                      style={{
                        borderRadius: "0 4px 4px 0",
                      }}>
                      评分
                    </Button>
                  </Space>
                </Space>
              </Col>
            </Row>
          }
          style={{
            backgroundColor: isDarkMode ? "#1f1f1f" : "#fff",
            border: isDarkMode ? "1px solid #434343" : "1px solid #d9d9d9",
          }}>
          <Spin spinning={commentsLoading}>
            {comments.length > 0 ? (
              <>
                <List
                  dataSource={comments}
                  renderItem={(comment) => {
                    console.log(
                      "🖼️ 渲染评论:",
                      comment.username,
                      "头像URL:",
                      comment.pic
                    );
                    return (
                      <List.Item
                        style={{
                          borderBottom: isDarkMode
                            ? "1px solid #434343"
                            : "1px solid #f0f0f0",
                          padding: "16px 0",
                        }}>
                        <List.Item.Meta
                          avatar={
                            comment.pic ? (
                              <Avatar
                                src={comment.pic}
                                style={{
                                  backgroundColor: "#1890ff",
                                }}
                              />
                            ) : (
                              <Avatar
                                icon={<UserOutlined />}
                                style={{
                                  backgroundColor: "#1890ff",
                                }}
                              />
                            )
                          }
                          title={
                            <div
                              style={{
                                display: "flex",
                                alignItems: "center",
                                gap: 12,
                              }}>
                              <Typography.Text
                                strong
                                style={{ color: isDarkMode ? "#fff" : "#000" }}>
                                {comment.username}
                              </Typography.Text>
                              <div
                                style={{
                                  display: "flex",
                                  alignItems: "center",
                                  gap: 4,
                                }}>
                                <Rate
                                  disabled
                                  value={comment.star / 2}
                                  allowHalf
                                  style={{ fontSize: 14 }}
                                />
                                <Typography.Text
                                  type="secondary"
                                  style={{ fontSize: 12 }}>
                                  {typeof comment.star === "number"
                                    ? comment.star.toFixed(1)
                                    : comment.star}
                                  分
                                </Typography.Text>
                              </div>
                              <Typography.Text
                                type="secondary"
                                style={{ fontSize: 12 }}>
                                {comment.createTime
                                  ? dayjs(comment.createTime).format(
                                      "YYYY-MM-DD HH:mm"
                                    )
                                  : "-"}
                              </Typography.Text>
                            </div>
                          }
                          description={
                            <div
                              style={{
                                marginTop: 8,
                                lineHeight: 1.6,
                                color: isDarkMode ? "#ccc" : "#666",
                              }}>
                              {comment.content}
                            </div>
                          }
                        />
                      </List.Item>
                    );
                  }}
                />

                {/* 分页 */}
                <div style={{ textAlign: "center", marginTop: 20 }}>
                  <Pagination
                    current={commentParams.page}
                    pageSize={commentParams.size}
                    total={commentsTotal}
                    onChange={handleCommentPageChange}
                    showSizeChanger
                    showQuickJumper
                    showTotal={(total, range) =>
                      `第 ${range[0]}-${range[1]} 条/共 ${total} 条`
                    }
                    pageSizeOptions={["5", "10", "20"]}
                  />
                </div>
              </>
            ) : (
              <Empty
                description="暂无评论，快来发表第一条评论吧！"
                style={{ margin: "40px 0" }}
              />
            )}
          </Spin>
        </Card>
      </div>
    </div>
  );
}
